/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.common.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * 二维码工具
 *
 * @author yoara
 */
public class QrCodeUtil {
    //二维码颜色
    private static final int BLACK = 0xFF000000;
    //二维码颜色
    private static final int WHITE = 0xFFFFFFFF;
    //字符集
    private static final String CHARSET = "utf-8";
    /**
     * 生成包含字符串信息的二维码图片
     *
     * @param outputStream 文件输出流路径
     * @param content      二维码携带信息
     * @param qrCodeSize   二维码图片大小
     * @param imageFormat  二维码的格式
     * @throws IOException
     */
    public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat)
            throws Exception {
        Map<EncodeHintType, String> his = new HashMap<>();
        //设置编码字符集
        his.put(EncodeHintType.CHARACTER_SET, CHARSET);
        //1、生成二维码
        BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, his);

        //2、获取二维码宽高
        int codeWidth = encode.getWidth();
        int codeHeight = encode.getHeight();

        //3、将二维码放入缓冲流
        BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < codeWidth; i++) {
            for (int j = 0; j < codeHeight; j++) {
                //4、循环将二维码内容定入图片
                image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
            }
        }
        //4、将二维码写入图片
        return ImageIO.write(image, imageFormat, outputStream);
    }

    /**
     * 解析二维码
     * @param stream 文件输入流
     */
    public static String decode(InputStream stream) throws Exception {
        BufferedImage image = ImageIO.read(stream);
        return decode(image);
    }

    /**
     * 解析二维码
     * @param iistream 图片文件输入流
     */
    public static String decode(ImageInputStream iistream) throws Exception {
        BufferedImage image = ImageIO.read(iistream);
        return decode(image);
    }

    /**
     * 解析二维码
     * @param file 文件
     */
    public static String decode(File file) throws Exception {
        BufferedImage image = ImageIO.read(file);
        return decode(image);
    }

    /**
     * 解析二维码
     * @param image 缓冲图片文件
     */
    public static String decode(BufferedImage image) throws Exception {
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }
}
